<script setup>
import { onMounted, ref } from 'vue';
import { List, Cell, Button,showSuccessToast, showFailToast } from 'vant';
import {getProcessDefinitionPage,onlineProcessDefinition,offlineProcessDefinition} from '@/api/dolphin.js';
import { useRoute } from 'vue-router';

const items = ref([]);
const loading = ref(false);
const finished = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const searchVal = ref('');

const router = useRoute();
// 从路由参数中获取 clusterId 和 projectCode
const clusterId = ref(router.params.clusterId || 'default-cluster-id');
const projectCode = ref(Number(router.params.projectCode) || 12345); // 确保转换为数字类型
// 初始化搜索结果
onMounted(() => {
  onSearch();
});

const onSearch = async () => {
  try {
    // 重置分页和加载状态
    console.log('开始搜索');
    currentPage.value = 1;
    items.value = [];
    loading.value = true;
    finished.value = false;

    const response = await getProcessDefinitionPage(clusterId.value, projectCode.value, currentPage.value, pageSize.value, searchVal.value);
    
    items.value.push(...(response.records || []));
    
    // 如果返回的结果少于请求的数量，则认为已经没有更多数据了
    if (response.totalPages <= response.currentPage) {
      finished.value = true;
    }

    loading.value = false;
    console.log('搜索完成', { items: items.value, finished: finished.value });
    console.log('currentPage.value:',{ currentPage:currentPage.value });
  } catch (error) {
    console.error('搜索工作流定义失败:', error);
    loading.value = false;
  }
};

const onCancel = () => {
  searchVal.value = '';
  // 清除搜索结果并重置状态
  items.value = [];
  loading.value = false;
  finished.value = false;
};



const onLoad = async () => {
  if (finished.value) return; // 如果已经完成加载，则不执行加载更多

  loading.value = true;

  try {
    console.log('开始加载更多');
    currentPage.value++;
    const response = await getProcessDefinitionPage(clusterId.value, projectCode.value, currentPage.value, pageSize.value, searchVal.value);
    items.value.push(...(response.records || []));
    console.log('加载更多完成', { items: items.value, finished: finished.value });
    console.log('currentPage.value:',{ currentPage:currentPage.value });
    // 当加载的数据达到总数量时，设置 finished 为 true
    if (response.totalPages <= response.currentPage) {
      finished.value = true;
    }
  } catch (error) {
    console.error('加载更多项目失败:', error);
  } finally {
    loading.value = false;
    console.log('加载更多完成', { items: items.value, finished: finished.value });
  }
};

// 截断文本并添加省略号
function truncateText(text, maxLength = 12) {
  return text.length > maxLength ? `${text.slice(0, maxLength)}...` : text;
}
// 下线
async function offline(item) {
  try {
    // 等待下线操作完成
    await offlineProcessDefinition(clusterId.value, projectCode.value, item.code);

    // 下线成功后重新搜索以刷新列表
    onSearch();
    
    // 可选: 显示成功的消息给用户
    showSuccessToast('下线成功');
  } catch (error) {
    // 处理错误情况
    console.error('下线失败:', error);
    // 可选: 显示错误信息给用户
    showFailToast('下线失败，请重试');
  }
}

// 上线
async function online(item) {
  try {
    // 等待下线操作完成
    await onlineProcessDefinition(clusterId.value, projectCode.value, item.code);

    // 下线成功后重新搜索以刷新列表
    onSearch();
    
    // 可选: 显示成功的消息给用户
    showSuccessToast('上线成功');
  } catch (error) {
    // 处理错误情况
    console.error('上线失败:', error);
    // 可选: 显示错误信息给用户
    showFailToast('上线失败，请重试');
  }
}



// 弹出层相关的状态管理
const showStartDialog = ref(false);
const currentItem = ref(null);

// // 表单数据
// const form = reactive({
//   failureStrategy: '',
//   processDefinitionCode: null,
//   processInstancePriority: '',
//   scheduleTime: new Date(),
//   warningGroupId: null,
//   warningType: '',
//   dryRun: 0,
//   environmentCode: '',
//   execType: '',
//   expectedParallelismNumber: '',
//   runMode: '',
//   startNodeList: '',
//   startParams: '',
//   taskDependType: '',
//   workerGroup: ''
// });

// 开始任务按钮点击事件
function onStart(item) {
  currentItem.value = item;
  // // 初始化表单数据
  // form.processDefinitionCode = item.code; // 假设 item 包含 code 属性
  showStartDialog.value = true;
}

// // 确认并开始任务
// async function onConfirm() {
//   try {
//     // 关闭弹出层
//     showStartDialog.value = false;

//     // 构建请求参数
//     const params = {
//       failureStrategy: form.failureStrategy,
//       processDefinitionCode: form.processDefinitionCode,
//       processInstancePriority: form.processInstancePriority,
//       scheduleTime: form.scheduleTime.toISOString(), // 或者根据 API 需求调整日期格式
//       warningGroupId: form.warningGroupId,
//       warningType: form.warningType,
//       dryRun: form.dryRun,
//       environmentCode: form.environmentCode,
//       execType: form.execType,
//       expectedParallelismNumber: form.expectedParallelismNumber,
//       runMode: form.runMode,
//       startNodeList: form.startNodeList,
//       startParams: form.startParams,
//       taskDependType: form.taskDependType,
//       workerGroup: form.workerGroup
//     };

//     // 调用 API 启动流程实例
//     const result = await startProcessInstance(
//       clusterId.value,
//       projectCode.value,
//       params
//     );

//     if (result) {
//       Toast.success('工作流实例启动成功');
//       // 刷新列表或其他后续操作
//       onSearch();
//     }
//   } catch (error) {
//     Toast.fail('工作流实例启动失败，请重试');
//     console.error('启动工作流实例失败:', error);
//   }
// }

// 取消并关闭弹出层
function onCancelDialog() {
  showStartDialog.value = false;
}

</script>

<template>
    <van-search
      v-model="searchVal"
      placeholder="工作流名称"
      show-action
      @search="onSearch"
      @cancel="onCancel"/>
    <van-list v-model:loading="loading" :finished="finished" @load="onLoad" :offset="100" finished-text="没有更多了">
      <van-cell 
      v-for="(item) in items"
      :key="item.id"
      :title="truncateText(item.name)"
      :label="item.releaseState"
      style="height: 60px;">
        <template #right-icon>
          <van-button round class="button-with-space" type="success" size="small" icon="play-circle-o" v-if="item.releaseState==='ONLINE'" @click="onStart(item)"></van-button>
          <van-button round class="button-with-space" color="#EBEAEA" size="small" icon="play-circle-o" v-else></van-button>
          <van-button round class="button-with-space" type="danger" size="small" icon="down"  v-if="item.releaseState==='ONLINE'" @click="offline(item)"></van-button>
          <van-button round class="button-with-space" type="warning" size="small" icon="back-top"  v-else @click="online(item)"></van-button>
          <van-button round class="button-with-space" type="primary" size="small" icon="clock-o"></van-button>
          <van-button round class="button-with-space" type="primary" size="small" icon="calendar-o"></van-button>
        </template>
      </van-cell>
    </van-list>

     <!-- 弹出层：运行任务表单 -->
    <van-popup v-model:show="showStartDialog" position="bottom" height="80%">
      <div style="padding: 20px;">
      <h3>配置并开始任务</h3>
      <!-- <div style="display: flex; align-items: center;">
      <span style="margin-right: 10px;">失败策略</span>
      <van-radio-group direction="horizontal" style="display: flex; gap: 10px;">
        <van-radio name="continue">继续</van-radio>
        <van-radio name="end">结束</van-radio>
      </van-radio-group>
      </div> -->
      <van-field label="优先级" placeholder="请输入优先级" />
      <van-datetime-picker type="datetime" title="选择调度时间" />
      <van-field label="警告组ID" placeholder="请输入警告组ID" />
      <van-field label="警告类型" placeholder="请输入警告类型" />
      <van-field label="Dry Run" placeholder="0 或 1" />
      <van-field label="环境代码" placeholder="请输入环境代码" />
      <van-field label="执行类型" placeholder="请输入执行类型" />
      <van-field label="预期并行数" placeholder="请输入预期并行数" />
      <van-field label="运行模式" placeholder="RUN_MODE_SERIAL 或 RUN_MODE_PARALLEL" />
      <van-field label="起始节点列表" placeholder="请输入起始节点列表" />
      <van-field label="启动参数" placeholder="请输入启动参数" />
      <van-field label="任务依赖类型" placeholder="请输入任务依赖类型" />
      <van-field label="Worker Group" placeholder="请输入Worker Group" />
      <div style="margin-top: 20px;">
        <van-button round block type="info" @click="onCancelDialog">取消</van-button>
        <van-button round block type="primary" @click="onConfirm" style="margin-top: 10px;">运行</van-button>
      </div>
    </div>
    </van-popup>
</template>

<style scoped>
.button-with-space {
  margin-right: 1px; /* 设置右侧间距 */
}

</style>
